<template>
	<view class="home">
		<u-navbar title="浮标法测流" :leftIconSize="24" bgColor="#f3f3f3" rightIcon="question-circle" :autoBack="true"
			:placeholder="true" safeAreaInsetTop>
			<view class="u-nav-slot" slot="right">
			</view>
		</u-navbar>
		<!-- 内容 -->
		<view class="concent_box">
			<view class="inibox">
				<view class="inibox_in">
					<view class="inibox_tt_a" hover-class="inibox_ttacv" @click="tobelFn" v-if="lanname == ''">点击连接设备
					</view>
					<view class="inibox_tt_b" hover-class="inibox_ttacv" @click="lampRFn" v-if="lanname != ''">点击断开设备
					</view>
				</view>
				<view class="inibox_in">
					<view class="inibox_tt_d" @click="joinwifiFn">
						<!-- 使用WebSocket组件 -->
						<advanced-websocket ref="socket" :url="socketUrl" :auto-connect="false" :heartbeat="{
						  message: 'heartCheck',
						  interval: 30000,
						  type: 'string'
						}" @connected="onConnected" @disconnected="onDisconnected" @message="onMessage" @error="onErrorHex"
							@status-change="onStatusChange" />
					</view>
				</view>
			</view>
			<view class="inibox">
				<view class="inibox_but" hover-class="inibox_acv" @click="iniIFFn">
					设备初始化
				</view>
			</view>
			<!-- 圈数 -->
			<view class="real_box">
				<view class="real_flx">
					<view class="real_l_a">
						<view class="buttn">
							<image class="img" src="@/static/zongx.png" mode=""></image>
						</view>
					</view>
					<view class="real_r_a">
						当前：{{yyNubAc}}
					</view>
				</view>
			</view>
			<!-- 遥控器 -->
			<view class="remoteControlUnit">

				<view class="container">
					<view class="clashow">
						{{showSlot}}
					</view>
					<!-- 深色模式苹果遥控器 -->
					<view class="dark-remote">
						<!-- 上按钮 -->
						<view class="dark-btn up-btn" @click="handleUpClick" @touchstart="startPress"
							@touchend="endPress">
							<view class="dark-btn-inner">
								<text class="icon">▲</text>
							</view>
						</view>

						<!-- 暂停按钮 -->
						<view class="dark-btn pause-btn" @click="handlePauseClick" @touchstart="startPress"
							@touchend="endPress">
							<view class="dark-btn-inner">
								<text class="icon">❚❚</text>
							</view>
						</view>

						<!-- 下按钮 -->
						<view class="dark-btn down-btn" @click="handleDownClick" @touchstart="startPress"
							@touchend="endPress">
							<view class="dark-btn-inner">
								<text class="icon">▼</text>
							</view>
						</view>
					</view>

					<!-- 触觉反馈指示器 -->
					<view class="haptic-indicator" :class="{ active: isPressed }">
						<view class="haptic-dot"></view>
					</view>
				</view>

			</view>
			<view class="" style="margin: 20rpx;">

			</view>
		</view>

		<!-- 初始化电机 -->
		<u-modal :show="infIF" title="初始化设备" @confirm="cinfconfirmIF" @cancel="infcancelIF" showCancelButton></u-modal>

		<!-- 选择设备弹窗 -->
		<u-popup :show="showpopup" mode="center" bgColor="transparent">
			<view class="claspopup">
				<!-- 选择设备 -->
				<custom-radio v-for="(item, index) in checkDataBox" :key="index" :label="item.label"
					:checked="selectedValue === item.value" @change="handleChange(item.value)" :fontSize="40"
					:iconSize="44" activeBgColor="#55aa7f" inactiveBgColor="#F8F8F8" activeTextColor="#F0F7FF"
					inactiveTextColor="#666666" activeBorderColor="#55aa7f" dotColor="#e5f0f9" :padding="24"
					:borderRadius="12" />
				<view class="" style="display: flex;justify-content: space-between;align-items: center;padding: 20rpx;">
					<u-button type="error" text="断开连接" @click="discDevice"></u-button>
					<view class="" style="width: 50rpx;">

					</view>
					<u-button type="success" text="连接设备" @click="connectingDevice"></u-button>
				</view>
				<view class="" style="display: flex;justify-content: space-between;align-items: center;padding: 20rpx;">
					<u-button type="primary" text="关闭弹窗" @click="closePopup"></u-button>
				</view>
			</view>
		</u-popup>
		<!-- wuxian  -->
	</view>
</template>

<script>
	import CustomRadio from "@/components/CustomRadio.vue";
	import advancedWebsocket from '@/components/websocket.vue'
	import calculatedDataFlow from '@/components/calculatedDataFlow.vue'
	import dayjs from '@/common/dayjs.min.js'
	const SixUniTts = uni.requireNativePlugin("SmallSix-SixUniTts")
	export default {
		components: {
			calculatedDataFlow,
			advancedWebsocket,
			CustomRadio
		},
		data() {
			return {
				selectedValue: "",
				showpopup: false, // 选择设备弹窗
				fontSize: '20px',
				connectionSuccessful: '', //4G连接成功
				socketUrl: '', //SocketTask地址
				checkDataBox: [], //设备列表
				columns: [], //设备列表
				yyNubAc: '', //脉冲数
				infIF: false, //初始化
				deviceId: '', //蓝牙
				serviceId: '', //蓝牙
				characteristicId: '', //蓝牙
				fff: '', //蓝牙
				lanname: '', //蓝牙
				showSlot: '暂停',
				showFeedback: false,
				isPressed: false
			}
		},
		onShow() {
			uni.showLoading({
				mask: true,
				title: '连接设备中...'
			});
			this.lanname = this.vuex_devicename
			this.deviceId = this.vuex_deviceId
			setTimeout(() => {
				uni.hideLoading()
			}, 300)
			this.getBLEDeviceServices()
			// 断开设备
			uni.onBLEConnectionStateChange((res) => {
				// 该方法回调中可以用于处理连接意外断开等异常情况
				if (res.connected !== true) {
					console.log('意外断开');
					this.lanname = ''
					uni.$u.vuex('vuex_devicename', '')
					uni.$u.vuex('vuex_deviceId', '')
				}
			})
		},
		onLoad(option) {
			// 保持屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: true
			});
		},
		onUnload() {
			console.log('卸载');
			// 销毁语音
			SixUniTts.destroy()
		},
		mounted() {
			// 初始化
			SixUniTts.initSixUniTts(res => {})
		},
		methods: {
			startPress() {
				this.isPressed = true;
				// iOS风格轻微震动
				uni.vibrateShort({
					type: 'light'
				});
			},
			endPress() {
				this.isPressed = false;
			},
			handleUpClick() {
				console.log("向上按钮点击");
				this.showFeedbackFn("向上");
				this.forwordFn()
			},
			handlePauseClick() {
				console.log("暂停按钮点击");
				this.showFeedbackFn("暂停");
				this.riseDevFnTHxx()
			},
			handleDownClick() {
				console.log("向下按钮点击");
				this.showFeedbackFn("向下");
				this.reversalFn()
			},
			showFeedbackFn(text) {
				this.showSlot = text
			},

			// 遥控器
			// 纵向按钮正转
			forwordFn() {
				console.log('上');
				// 点位参数
				let hposData = ['0x01', '0x10', '0x60', '0x81', '0x00', '0x04', '0x08', '0x00', '0x00', '0x00', '0xC8',
					'0x00', '0x64', '0x00', '0x64', '0x69', '0x83'
				]
				let initiate = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x0F', '0xD6', '0x1A']
				this.conbuffer(hposData)
				setTimeout(() => {
					this.conbuffer(initiate)
				}, 300)

			},
			// 纵向按钮反转
			reversalFn() {
				console.log('下');
				let hposData = ['0x01', '0x10', '0x60', '0x81', '0x00', '0x04', '0x08', '0xFF', '0xFF', '0xFF', '0x38',
					'0x00', '0x64', '0x00', '0x64', '0x7D', '0x92'
				]
				let initiate = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x0F', '0xD6', '0x1A']
				this.conbuffer(hposData)
				setTimeout(() => {
					this.conbuffer(initiate)
				}, 300)
			},
			// 松开暂停
			riseDevFnTHxx() {
				console.log('松开暂停');
				let pause = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x07', '0xD7', '0xDC']
				this.conbuffer(pause)
			},
			// 询问横向地址脉冲圈数
			aLLBrakeFnxx() {
				let brake = ['0x01', '0x03', '0x60', '0x64', '0x00', '0x02', '0x9B', '0xD4']
				this.conbuffer(brake)
			},
			// 询问纵向地址脉冲圈数
			aLLBrakeFnyy() {
				let brake = ['0x02', '0x03', '0x60', '0x64', '0x00', '0x02', '0x9B', '0xE7']
				this.conbuffer(brake)
			},

			// 初始化
			iniIFFn() {
				this.infIF = true
			},

			// 初始化电机确定
			cinfconfirmIF() {
				this.iniFn()
				this.infIF = false
			},
			// 初始化电机取消
			infcancelIF() {
				this.infIF = false
			},
			// 脉冲清零归零模式
			iniFn() {
				uni.showToast({
					title: '正在初始化...',
					icon: 'loading',
					mask: true,
					duration: 10000
				});
				// 驱动器上电初始化
				let ini = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x01', '0x57', '0xDE']
				// 驱动器正常运行，但电机未使能，松开刹车
				let brakeDel = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x03', '0xD6', '0x1F']
				// 电机给电，处于可运行状态
				let electric = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x0F', '0xD6', '0x1A']
				// 设置回零模式 01 06 60 60 00 06 17 D6
				let hpos = ['0x01', '0x06', '0x60', '0x60', '0x00', '0x06', '0x17', '0xD6']
				// 设定回零方式 01 10 60 7C 00 08 10 00 00 03 E8 00 01 00 00 00 64 03 E8 00 00 00 64
				let hposTop = ['0x01', '0x10', '0x60', '0x7C', '0x00', '0x08', '0x10', '0x00', '0x00', '0x03', '0xE8',
					'0x00', '0x01', '0x00', '0x00', '0x00', '0x64', '0x03', '0xE8', '0x00', '0x00', '0x00', '0x64',
					'0x0D', '0xBE'
				]
				// 开始归零
				let startToZero = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x1F', '0xD7', '0xD6']
				this.conbuffer(ini)
				setTimeout(() => {
					this.conbuffer(brakeDel)
				}, 300)
				setTimeout(() => {
					this.conbuffer(electric)
				}, 600)
				setTimeout(() => {
					this.conbuffer(hpos)
				}, 900)
				setTimeout(() => {
					this.conbuffer(hposTop)
				}, 1200)
				setTimeout(() => {
					this.conbuffer(startToZero)
					setTimeout(() => {
						this.verticalZeroingYY()
					}, 300)
				}, 1500)
			},
			// 横向初始化
			verticalZeroingYY() {
				clearInterval(this.landscapeOrientationXX)
				// 驱动器上电初始化
				let ini = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x01', '0x57', '0xDE']
				// 驱动器正常运行，但电机未使能，松开刹车 
				let brakeDel = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x03', '0xD6', '0x1F']
				// 电机给电，处于可运行状态
				let electric = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x0F', '0xD6', '0x1A']
				// 暂停电机运行
				let hposTop = ['0x01', '0x06', '0x60', '0x40', '0x01', '0x0F', '0xD7', '0x8A']
				// 设置速度模式
				let hpos = ['0x01', '0x06', '0x60', '0x60', '0x00', '0x03', '0xD7', '0xD5']

				this.conbuffer(ini)
				setTimeout(() => {
					this.conbuffer(brakeDel)
				}, 300)
				setTimeout(() => {
					this.conbuffer(electric)
				}, 600)
				setTimeout(() => {
					this.conbuffer(hposTop)
				}, 900)
				setTimeout(() => {
					this.conbuffer(hpos)
				}, 1200)
			},
			// wuxian
			// 选择设备
			discDevice() {
				this.showpopup = false
				this.duankai()
				this.selectedValue = '';
				console.log('取消连接');
				// this.showpopup = false
			},
			connectingDevice() {
				if (this.selectedValue == '') {
					return
				} else {
					// 根路径
					let url = 'ws://' + uni.$u.http.config.baseURL.substring(7) + '/websocket/message/device/' + this
						.selectedValue
					this.socketUrl = url
					console.log('url', this.socketUrl);
					this.showpopup = false
					// 连接
					setTimeout(() => {
						this.reconnect()
					}, 500)
					console.log('连接', this.selectedValue);
				}
			},
			closePopup() {
				this.showpopup = false
			},
			// 选择设备
			handleChange(value) {
				this.selectedValue = value;
				console.log('设备id', value);
			},
			// 点击链接设备
			joinwifiFn() {
				this.showpopup = true
			},
			// 断开
			duankai() {
				this.connectionSuccessful = ''
				this.$refs.socket.disconnect()
			},
			// // 连接成功回调
			onConnected() {
				this.connectionSuccessful = '4G连接成功'
				console.log('4G连接成功', this.connectionSuccessful);
			},

			// 连接断开回调
			onDisconnected() {
				this.connectionSuccessful = ''
				console.log('系统', 'WebSocket连接断开');
			},

			// 状态变化回调
			onStatusChange(status) {
				console.log('系统状态变更为:', status);
			},

			// 错误回调
			onErrorHex(err) {
				console.log('错误', err.message);
			},

			// 收到消息回调
			onMessage(msg) {
				let str = this.removeTrailingSubstring(msg, '4552524f523d3130340d0a')
				console.log('str', str);
				this.monitoringInformationProcessing(str)
				// let ask = this.hexToString(msg)
				// console.log('ask+++++++++++++',ask);
				if (msg == '未找到设备连接' || msg == 'DeviceOffline') {
					this.duankai()
				}
				console.log('接收***', msg, msg.length);
			},

			// 发送字节数组
			async sendBytes(data) {
				if (this.connectionSuccessful != '4G连接成功') {
					return
				}
				console.log('发送', data);
				try {
					await this.$refs.socket.sendBytes(data)
				} catch (err) {
					this.onErrorHex(err)
				}
			},
			// 接受指令传输
			byteArray(data) {
				this.sendBytes(data)
			},
			// 重新连接
			reconnect() {
				this.$refs.socket.connect()
				// this.$refs.socket.reconnect()
			},

			// 发送16进制字符串
			async sendHex() {
				try {
					await this.$refs.socket.sendHex('41542a44545549503f')
				} catch (err) {
					this.onErrorHex(err)
				}
			},
			// 设备列表
			deviceListFn() {
				uni.$u.http.get('/device/device/geiCeLiuCheList').then(res => {
					if (res.code == 200) {
						this.columns = []
						let arr = []
						arr = res.rows.map((i) => {
							return {
								label: i.nickName,
								id: i.id,
								value: i.id,
							}
						})
						this.columns.push(arr)
						this.checkDataBox = arr
					}
				}).catch(err => {
					console.log('错误', err);
				})
			},
			// wuxian
			// 输入蓝牙数据
			conbuffer(data) {
				if (this.lanname == '') {
					this.byteArray(data)
				} else {
					let msg = data
					console.log('发送数据格式蓝牙', data);
					// 向蓝牙设备发送一个0x00的16进制数据
					const buffer = new ArrayBuffer(msg.length)
					const dataView = new DataView(buffer)
					// dataView.setUint8(0, 0)
					for (var i = 0; i < msg.length; i++) {
						// dataView.setUint8(i, msg.charAt(i).charCodeAt())
						dataView.setUint8(i, msg[i]);
					}
					this.sendMsgToKey(buffer)
				}
			},
			//监听消息变化++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			listenValueChange(data) {
				setTimeout(() => {
					uni.onBLECharacteristicValueChange(res => {

						if (this.lanname != '') {
							let resHex = this.ab2hex(res.value)
							this.monitoringInformationProcessing(resHex)
						} else {
							this.monitoringInformationProcessing(res)
						}
					})
				}, 300)
			},
			monitoringInformationProcessing(res) {
				let resHex = res
				console.log('监听数据', resHex, resHex.length);
				// 获取脉冲xx
				if (resHex.substr(0, 6) == '010304' && resHex.length == 18) {
					let str = resHex.substr(6, 8)
					this.yyNubAc = (this.hexToDecimal(str) / 10000 / 50 * 0.305).toFixed(2)
				}
			},
			//获取蓝牙的所有服务
			getBLEDeviceServices() {
				setTimeout(() => {
					uni.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.vuex_deviceId,
						success: (res) => {
							console.log('获取vuex_deviceId', this.vuex_deviceId);
							console.log('获取蓝牙所有服务', res);
							//E95D93AF-251D-470A-A062-FA1922DFA9A8
							//6E400001-B5A3-F393-E0A9-E50E24DCCA9E
							res.services.forEach((item) => {

								if (item.uuid.indexOf("0000FFF0") != -1) {
									this.serviceId = item.uuid;
									//获取特征
									this.getBLEDeviceCharacteristics()
								}
								if (item.uuid.indexOf("0000FFE0") != -1) {
									this.serviceId = item.uuid;
									//获取特征
									this.getBLEDeviceCharacteristics()
								}
								if (item.uuid.indexOf("00001000") != -1) {
									this.serviceId = item.uuid;
									//获取特征
									this.getBLEDeviceCharacteristics()
								}
							})
						}
					})
				}, 1000)
			},
			//获取蓝牙特征
			getBLEDeviceCharacteristics() {
				console.log('获取蓝牙特征值', this.deviceId, this.serviceId, );
				setTimeout(() => {
					uni.getBLEDeviceCharacteristics({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.deviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: this.serviceId,
						success: (res) => {

							this.characteristics = res.characteristics
							res.characteristics.forEach((item) => {

								if (item.uuid.indexOf("FFF2") != -1) {
									this.fff = item.uuid
								}
								if (item.uuid.indexOf("FFE1") != -1) {
									this.fff = item.uuid
								}
								if (item.uuid.indexOf("0000FFE1") != -1) {
									this.characteristicId = item.uuid
									//利用传参的形势传给下面的notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
								if (item.uuid.indexOf("0000FFF1") != -1) {
									this.characteristicId = item.uuid
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
								// EW-DTU02
								if (item.uuid.indexOf("00001001") != -1) {
									this.fff = item.uuid
								}
								if (item.uuid.indexOf("00001002") != -1) {
									this.characteristicId = item.uuid
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
							})
						},
						fail: (res) => {
							console.log(res)
						}
					})
				}, 1000)
			},
			// 删除指定字符串最后面
			removeTrailingSubstring(str, suffix) {
				if (!str || !suffix) return str;

				const strLength = str.length;
				const suffixLength = suffix.length;

				// 检查字符串是否以指定的子串结尾
				if (strLength >= suffixLength &&
					str.substring(strLength - suffixLength) === suffix) {
					return str.substring(0, strLength - suffixLength);
				}

				return str;
			},
			// 16进制转2进制
			hexToBinaryW(hexString) {
				if (!/^[0-9A-Fa-f]+$/.test(hexString)) {
					throw new Error("Invalid hexadecimal string");
				}
				const decimal = parseInt(hexString, 16);
				return decimal.toString(2);
			},
			// 10进制转32位二进制补码
			NumberOf1(num) {
				// 获取负数的绝对值
				const absoluteValue = Math.abs(num);

				// 将绝对值转换为32位二进制字符串
				let binaryString = absoluteValue.toString(2);

				// 确保二进制字符串长度为32位
				while (binaryString.length < 32) {
					binaryString = '0' + binaryString;
				}

				// 对二进制字符串取反
				const invertedBinaryString = binaryString.split('').map(bit => bit === '0' ? '1' : '0').join('');

				// 将取反后的二进制字符串转换为数字并加1
				const twosComplement = parseInt(invertedBinaryString, 2) + 1;

				// 再次将补码转换为32位二进制字符串
				binaryString = twosComplement.toString(2);
				// 确保二进制字符串长度为32位
				while (binaryString.length < 32) {
					binaryString = '0' + binaryString;
				}

				return binaryString;
			},
			// 二进制补码转16进制
			binaryToHex(binaryStr) {
				// 确保二进制字符串是32位
				if (binaryStr.length !== 32) {
					throw new Error('Binary string must be 32 bits long');
				}

				// 将二进制字符串转换为数字
				var number = parseInt(binaryStr, 2);

				// 转换为16进制并返回结果
				return number.toString(16);
				// 示例使用
				// var binaryStr = '010101010101010101010101010101010'; // 32位二进制补码
				// var hexStr = binaryToHex(binaryStr);
			},
			//数组求平均
			averageSum(arr) {
				if (arr.length === 0) {
					return 0; // 当数组为空时，平均值为0
				}

				let sum = 0;
				for (let i = 0; i < arr.length; i++) {
					sum += arr[i];
				}

				return sum / arr.length;
			},
			// 长度不够补0
			strRepair(str, nub) {
				let nubm = nub * 1
				let strif = str + ''
				if (strif.length < nubm) {
					for (let i = 0; i < nubm - str.length; i++) {
						strif = '0' + strif
					}
				}
				return strif
			},
			//给每个数组添加0x
			ocstr(data) {
				let arr = []
				for (let i = 0; i < data.length; i++) {
					data[i] = '0x' + data[i]
				}
				return data
			},
			// 每2个字符串为一个元素数组
			chunkStringByTwo(str) {
				const result = [];
				for (let i = 0; i < str.length; i += 2) {
					result.push(str.slice(i, i + 2));
				}
				return result;
			},
			// 处理ASCLL 30 -00
			ascllFn(data) {
				let str = data + ''
				let arr = this.chunkStringByTwo(str)

				for (let i = 0; i < arr.length; i++) {
					if (arr[i] == '00') {
						arr[i] = '30'
					}
				}
				let arrnew = arr

				let strnre = ''
				for (let i = 0; i < arrnew.length; i++) {
					strnre += arrnew[i]
				}
				return strnre
			},
			// CRC16校验
			crc16(dataHexString) {
				const dataBytes = [];
				for (let i = 0; i < dataHexString.length; i += 2) {
					dataBytes.push(parseInt(dataHexString.substr(i, 2), 16));
				}

				let crc = 0xFFFF;
				const polynomial = 0xA001;

				for (const byte of dataBytes) {
					crc ^= byte;
					for (let i = 0; i < 8; i++) {
						if (crc & 0x0001) {
							crc = ((crc >> 1) ^ polynomial) & 0xFFFF;
						} else {
							crc >>= 1;
						}
					}
				}
				let crcstr = crc.toString(16).toUpperCase();
				if (crcstr.length % 2 == 0) {
					let result = crcstr.match(/.{1,2}/g)
					return result;
				} else {
					let str = '0' + crcstr
					let result = str.match(/.{1,2}/g)
					return result;
				}
			},
			// 16进制转10进制
			hexToDecimal(hex) {
				return parseInt(hex, 16);
			},
			// 10进制转16进制
			decimalToHex(data) {
				let decimal = data * 1
				let hex = decimal.toString(16).toUpperCase();
				3
				if (hex.length % 2 !== 0) {
					return '0' + hex
				} else {
					return hex
				}
				// return decimal.toString(16).toUpperCase();
			},
			// 16进制转字符串 ASCII码
			hexToString(hex) {
				let str = '';
				for (let i = 0; i < hex.length; i += 2) {
					let charCode = parseInt(hex.substr(i, 2), 16);
					str += String.fromCharCode(charCode);
				}
				return str;
			},

			//字符串转16进制
			stringToHex(data) {
				let str = data + ''
				return str.split('').map(function(char) {
					return char.charCodeAt(0).toString(16).padStart(2, '0');
				}).join('');
			},
			// 16进制转汉字
			hexToChinese(hex) {
				var str = '';
				for (var i = 0; i < hex.length / 4; i++) {
					var codePoint = parseInt(hex.substr(i * 4, 4), 16); // 获取每四位的十六进制值并转换成十进制
					str += String.fromCharCode(codePoint); // 根据Unicode编码生成对应的字符
				}
				return str;
			},
			// 汉字转16进制
			convertToHex(str) {
				let result = '';
				for (let i = 0; i < str.length; i++) {
					result += str.charCodeAt(i).toString(16);
				}
				return result;
			},
			// 随机数
			getRandomNumber(min, max) {
				return Math.floor(Math.random() * (max - min + 1)) + min;
			},
			// 删除最小的前面几个数字
			removeSmallestN(arr, n) {
				// 对数组进行升序排序
				const sorted = arr.sort((a, b) => a - b);
				// 删除最前面的n个数字
				sorted.splice(0, n);
				return sorted;
			},
			// 删除最大的后面几个数字
			removeMax(arr, n) {
				// 对数组进行升序排序
				const sorted = arr.sort((a, b) => a - b);
				// 删除最后面的n个数字
				sorted.splice(-n);
				return sorted;
			},
			// ArrayBuffer转16进度字符串示例
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			/* 向设备发送消息(分包发送，单包20字节，递归发送)
			 */
			sendMsgToKey(buffer) {
				var that = this //vue中的this
				const packageSize = 20 //分包大小
				if (buffer.byteLength <= 20) { //如果小于20直接发送，不再继续调用
					uni.writeBLECharacteristicValue({
						// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
						deviceId: that.deviceId,
						// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
						serviceId: that.serviceId,
						// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
						// characteristicId: that.fff, //第二步写入的特征值
						characteristicId: that.fff, //第二步写入的特征值
						// 这里的value是ArrayBuffer类型
						value: buffer,
						writeType: 'write',
						success: (res) => {
							//此时设备已接收到你写入的数据
							console.log('写入11111');

						},
						fail: (err) => {
							console.log('传输失败', err)
							this.lanname = this.vuex_devicename
						},
						complete: function() {}
					})
				} else { //如果大于20发送完成后继续递归调用
					var newData = buffer.slice(20)
					var writeBuffer = buffer.slice(0, 20)
					uni.writeBLECharacteristicValue({
						// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
						deviceId: that.deviceId,
						// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
						serviceId: that.serviceId,
						// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
						characteristicId: that.fff, //第二步写入的特征值
						// 这里的value是ArrayBuffer类型
						value: writeBuffer,
						writeType: 'write',
						success: function(res) {
							console.log('写入22222');
							//写入后继续递归调用发送剩下的数据
							setTimeout(() => {
								that.sendMsgToKey(newData)
							}, 100)
						},
						fail: (err) => {
							this.lanname = this.vuex_devicename
							console.log('传输失败', err)
						},
						complete: function() {}
					})
				}
			},
			// 启用 notify 功能
			notifyBLECharacteristicValueChange(characteristicId) {
				console.log('启用 notify 功能');
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: this.deviceId,

					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: this.serviceId,
					// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
					characteristicId: this.characteristicId,
					success: (res) => {
						console.log('蓝牙名字', res);
						// vuex
						// uni.$u.vuex('vuex_devicename', this.vuexlist.name)
						uni.hideLoading()
						this.listenValueChange()
						uni.showToast({
							title: '设备已连接',
							mask: true,
							duration: 1000
						});
						console.log('蓝牙服务已开启');
					},
					fail: (res) => {
						uni.hideLoading()
						uni.showToast({
							title: '连接设备失败',
							icon: 'fail',
							mask: true,
							duration: 1000
						});

					}
				})
			},
			// 删除数组
			removeById(arr, id) {
				for (let i = 0; i < arr.length; i++) {
					if (arr[i].id === id) {
						arr.splice(i, 1);
						break;
					}
				}
				return arr;
			},
			// 生Id
			nanoid(size = 21) {
				let id = ''
				let i = size
				while (i--) {
					id += this.urlAlphabet[(Math.random() * 64) | 0]
				}
				return id
			},
			// 蓝牙
			tobelFn() {
				//在起始页面跳转到test.vue页面并传递参数
				uni.navigateTo({
					url: '/pages/index/devBEL'
				});

			},
			//断开连接
			lampRFn() {
				uni.closeBLEConnection({
					deviceId: this.vuex_deviceId,
					success: (res) => {
						uni.showToast({
							title: '设备已断开',
							icon: 'success',
							mask: true,
							duration: 1000
						});
						this.lanname = ''
						uni.$u.vuex('vuex_devicename', '')
					}
				})
			},
		}
	}
</script>
<style lang="scss" scoped>
	/* 深色模式基础样式 */
	.container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		// height: 100vh;
		// background-color: #000000;
		/* 纯黑背景 */
		.clashow {
			font-size: 50rpx;
			color: #1c1c1e;
			line-height: 100rpx;
			text-align: center;
		}
	}

	/* 遥控器主体 */
	.dark-remote {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 280rpx;
		background-color: #f3f3f3;
		/* 深灰背景 */
		border-radius: 60rpx;
		padding: 20rpx;
		border: 1rpx solid #2c2c2e;
		/* 微妙边框 */
		box-shadow:
			0 10rpx 30rpx rgba(0, 0, 0, 0.5),
			inset 0 1rpx 1rpx rgba(255, 255, 255, 0.05);
	}

	/* 按钮基础样式 */
	.dark-btn {
		width: 220rpx;
		height: 220rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 16rpx 0;
		background-color: rgba(0, 0, 0, 0.8);
		/* 深灰按钮 */
		position: relative;
		overflow: hidden;
		transition: transform 0.1s, background-color 0.1s;
	}

	/* 按钮按下效果 */
	.dark-btn:active {
		transform: scale(0.96);
		background-color: #3a3a3c;
	}

	/* 按钮内部 */
	.dark-btn-inner {
		width: 160rpx;
		height: 160rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		background: linear-gradient(145deg, #2c2c2e, #1c1c1e);
		box-shadow:
			inset 0 2rpx 4rpx rgba(0, 0, 0, 0.5),
			inset 0 -2rpx 4rpx rgba(255, 255, 255, 0.05);
	}

	/* 按钮图标 */
	.icon {
		font-size: 60rpx;
		font-weight: 300;
	}

	.up-btn .icon {
		font-size: 80rpx;
		color: #00efaf;
		/* 苹果深色模式绿色 */
		margin-bottom: 10rpx;
	}

	.pause-btn .icon {
		font-size: 80rpx;
		color: #ff6060;
		/* 苹果深色模式红色 */
		font-size: 50rpx;
	}

	.down-btn .icon {
		font-size: 80rpx;
		color: #00efaf;
		/* 苹果深色模式绿色 */
		margin-top: 10rpx;
	}

	/* 触觉反馈指示器 */
	.haptic-indicator {
		margin-top: 50rpx;
		opacity: 0;
		transition: opacity 0.3s;
	}

	.haptic-indicator.active {
		opacity: 0.8;
	}

	.haptic-dot {
		width: 6rpx;
		height: 6rpx;
		border-radius: 50%;
		background-color: #30d158;
		box-shadow: 0 0 10rpx #30d158;
	}
</style>
<style scoped lang="scss">
	// 历史记录遮罩
	.overlay-wrap {
		@include flex;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		flex: 1;

		.box_a {
			padding: 30rpx;
			margin: 30rpx;
			border-radius: 30rpx;
			border: 5rpx solid rgba(170, 255, 255, 0.5);
			color: #00ffe2;
			font-size: 60rpx;
			background-color: rgba(0, 0, 0, 0.9);
		}
	}

	// 内容
	.concent_box {
		padding: 0 30rpx 30rpx 30rpx;

		.inibox {
			margin: 20rpx 0;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.inibox_but {
				width: 690rpx;
				text-align: center;
				color: #ffffff;
				font-size: 30rpx;
				padding: 20rpx 0;
				border-radius: 200rpx;
				background-color: #594e6f;
			}

			.inibox_in {
				width: 330rpx;

				.inibox_tt_a {
					text-align: center;
					color: #ffffff;
					font-size: 30rpx;
					padding: 20rpx 0;
					border-radius: 200rpx;
					background-color: #bd0000;
				}

				.inibox_tt_b {
					text-align: center;
					color: #ffffff;
					font-size: 30rpx;
					padding: 20rpx 0;
					border-radius: 200rpx;
					background-color: #00b457;
				}

				.inibox_tt_d {
					// width: 250rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					// text-align: center;
					// color: #ffffff;
					// font-size: 30rpx;
					// padding: 20rpx 0;
					// border-radius: 200rpx;
					// background-color: #00aaff;
				}

				.inibox_ttacv {
					color: #ffffff;
					background-color: #d0d4d4;
				}
			}

			.inibox_in {
				width: 330rpx;

				.inibox_tt_a {
					text-align: center;
					color: #ffffff;
					font-size: 30rpx;
					padding: 20rpx 0;
					border-radius: 200rpx;
					background-color: #bd0000;
				}

				.inibox_tt_b {
					text-align: center;
					color: #ffffff;
					font-size: 30rpx;
					padding: 20rpx 0;
					border-radius: 200rpx;
					background-color: #00b457;
				}

				.inibox_ttacv {
					color: #ffffff;
					background-color: #d0d4d4;
				}
			}


			.inibox_acv {
				color: #ffffff;
				background-color: #d0d4d4;
			}
		}


		.lamp_a {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 30rpx;

			.lamp_l_a {
				width: 50rpx;
				height: 50rpx;
				border-radius: 100rpx;
				background-color: #c2e2cc;
				box-shadow: inset 0 0 20rpx rgba(0, 0, 0, 0.3);
			}

			.lamp_r_a {
				width: 50rpx;
				height: 50rpx;
				border-radius: 100rpx;
				background-color: #ff0000;
				box-shadow: inset 0 0 20rpx rgba(0, 0, 0, 0.3);
			}
		}

		// 遥控器
		.remoteControlUnit {}
	}


	// 行走圈数
	.real_box {
		padding: 20rpx;
		margin: 20rpx 0;
		background-color: #fafafa;
		border-radius: 100rpx;
		border: 3rpx solid #fff;
		padding: 10rpx;
		box-shadow: 0 0 15rpx rgba(127, 127, 127, 0.2);

		.real_flx {
			display: flex;
			align-items: center;
			justify-content: space-between;
			color: #000000;

			.real_l_a {
				font-size: 45rpx;

				.buttn {
					padding: 15rpx;
					border-radius: 100rpx;
					display: flex;
					justify-content: space-around;
					align-items: center;
					background-color: #52c8ab;

					.img {
						width: 100rpx;
						height: 100rpx;
						// margin-right: 20rpx;
					}
				}
			}

			.real_r_a {
				font-size: 60rpx;
				width: 500rpx;
				text-align: left;
				border-radius: 20rpx 200rpx 200rpx 20rpx;
				padding: 10rpx;
				// font-family: 'MyFont';
				background-color: #000000;
				color: #33ff9e;
			}
		}

		.text {
			margin: 20rpx auto;
			width: 450rpx;
			text-align: center;
			border-radius: 20rpx;
			background-color: #000000;
			color: #6eff42;

			.aa {
				font-size: 30rpx;
			}

			.bb {
				font-size: 40rpx;
				font-family: 'MyFont';
			}
		}
	}


	// 选择设备
	.claspopup {
		width: 600rpx;
		margin: 0 auto;
		padding: 30rpx;
		border-radius: 30rpx;
		background-color: #ffffff;

	}
</style>
<style>
	page {
		background-color: #f3f3f3;
	}
</style>